-- 篮球计数器
-- 30s倒计时
-----------------

entity countdown is
    port(
        clk, clear, en : in std_logic;
        buzzer : out std_logic;
        led : out std_logic_vector(7 downto 0);     -- 数码分段abcdefg
        led_s : out std_logic_vector(1 downto 0);   -- 2个led扫描标志
        led0 : out std_logic_vector(3 downto 0);    -- led0值
        led1 : out std_logic_vector(1 downto 0)    -- led1值
    );
end countdown;

architecture behave of countdown is
    signal down_clk : std_logic_vector(1 downto 0);
    signal down_clk_change : std_logic;
    signal led_split : std_logic;
begin

    -- 1s倒计时
    process(clk) then
        if rising_edge(clk) then
            if down_clk = "10" then
                down_clk_change <= not down_clk_change;
                down_clk <= (others => '0');
            else
                down_clk <= down_clk + 1;
            end if;
        end if;
    end process;

    -- led值设置
    process(clear, down_clk) begin
        if clear = '1' then
            led1 <= "11"; led0 <= "0000"; buzzer <= '0'; -- 默认显示30
        elsif clear = '0' and rising_edge(down_clk) and en = '1' then
            if led0 = "0000" then
                if led1 = "00" then
                    led1 <= "11"; led0 <= "0000"; buzzer <= '1'; --倒计时结束，响铃，重新设置为30
                else                    
                    led1 <= led1 - 1; led0 = "1001"; buzzer <= '0';
                end if;
            else
                led0 <= led0 - 1; buzzer <= '0';
            end if;
        end if;
    end process;

    -- led分频
    process(clk) begin
        if rising_edge(clk) then
            if led_split = '0' then 
                led_split <= '1';
            else
                led_split <= '0';
            end if;
        end if;
    end process;

    -- led分段设置
    process(clk) begin
        if led_split = '0' then
            case led0 is
                when "0000" => led <= "";
                when "0001" => led <= "";
                when "0010" => led <= "";
                when "0011" => led <= "";
                when "0100" => led <= "";
                when "0101" => led <= "";
                when "0110" => led <= "";
                when "0111" => led <= "";
                when "1000" => led <= "";
                when "1001" => led <= "";
            end case;
        elsif led_split = '1' then
            case led1 is
                when "00" => led <= "";
                when "01" => led <= "";
                when "10" => led <= "";
                when "11" => led <= "";
            end case;
        end if;
    end process;

end behave;
